package com.hyzh.latte.util.gather;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hyzh.latte.vehicle.dmo.*;
import com.hyzh.latte.vehicle.dmo.entity.ParkPGEntity;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author songkui
 * @since 2024/4/23 20:42
 */
@Slf4j
public class OkhttpUtil {
   /* public static void doPostMZ(MianzhuVehicleTrackData msg){
        OkHttpClient client = new OkHttpClient();

        // 创建自定义对象
        // 将自定义对象转换为 JSON 字符串
        String jsonBody = JSON.toJSONString(msg, SerializerFeature.PrettyFormat);

        // 构建请求体
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        // 构建 POST 请求
        Request request = new Request.Builder()
                .url("http://172.21.20.14:18915/me/public/rs/api/third/realtime/data")
                .post(requestBody)
                .build();

        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 获取响应内容
            String responseBody = response.body().string();
            log.info("172.21.20.14 Response: " + responseBody);
        } catch (IOException e) {
           log.error("okhttp", e);
        }

    }*/
    public static StreamResponse doPostStream(StreamRequest msg, String url){
        OkHttpClient client = new OkHttpClient().newBuilder() .build();
        String jsonBody = JSON.toJSONString(msg, SerializerFeature.PrettyFormat);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonBody);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            String responseBody = response.body().string();
            log.info("Response BIZ: " + responseBody);
            return JSON.parseObject(responseBody, StreamResponse.class);
        } catch (IOException e) {
           log.error("okhttp", e);
        }

        return null;
    }

    public static void doPost(List<EarlyWarningPublicDTO> msg, String url){
        if (CollectionUtil.isEmpty(msg)){
            return;
        }

        OkHttpClient client = new OkHttpClient();
        String jsonBody = JSON.toJSONString(msg, SerializerFeature.PrettyFormat);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            String responseBody = response.body().string();
            log.info("Response BIZ: " + responseBody);
        } catch (IOException e) {
           log.error("okhttp", e);
        }

    }


    public static byte[] findScreenshot(ScreenshotRequest param, String park, String url){
        String secret = Objects.requireNonNull(StreamingSecretEnum.ofCode(park)).code();
        String local = "http://127.0.0.1/live/%s.live.flv";
        String urlLast = "/index/api/getSnap?url=%s&timeout_sec=10&expire_sec=1&secret="+secret;
        String allUrl = url +  String.format(urlLast, StrUtil.isNotEmpty(param.getUrl()) ? param.getUrl() : String.format(local, param.getCno()));
        log.info("Screenshot-URL: {}", allUrl);
        Request request = new Request.Builder()
                .url(allUrl)
                .get()
                .build();

        try {
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                assert response.body() != null;
                log.info("Screenshot contentLength: {}", response.body().contentLength());
                return response.body().bytes();
            } else {
                log.error("Screenshot error:  url {}; ", allUrl);
            }
        } catch (Exception e) {
            log.error("Screenshot error: {}", e.getMessage());
        }
        return null;
    }

    public static List<StreamDataResponse> pullStreamByTime(LocalDateTime startDateTime, LocalDateTime endDateTime, String cno, ParkPGEntity parkEntity, String park){
        long st = startDateTime.toEpochSecond(ZoneOffset.of("+8"));
        long et = endDateTime.toEpochSecond(ZoneOffset.of("+8"));

        if (cno.contains(",")){
            List<StreamDataResponse> data = new ArrayList<>();
            String[] cnos = cno.split(",");
            for (String c : cnos){
                List<StreamDataResponse> list =  pullStream(c, st, et, parkEntity.getStreamUrl(), park);
                if (CollectionUtil.isNotEmpty(list)){
                    data.addAll(list);
                }
            }
            if (CollectionUtil.isEmpty(data)){
                return null;
            }
            return data;
        }

        return OkhttpUtil.pullStream(cno, st, et, parkEntity.getStreamUrl(), park);
    }


    //历史视频流
    public static List<StreamDataResponse> pullStream(String cno, long st, long et, String url, String park){

        try {
            final String api = "/v2/smc/web/getmergeurl_v2";

            List<StreamDataRequest> sl = new ArrayList<>(1);
            sl.add(new StreamDataRequest(1, cno, st, et));
            StreamResponse response = OkhttpUtil.doPostStream(new StreamRequest(sl), url+api);
            if (null == response || CollectionUtil.isEmpty(response.getData())){
                log.info("historyStream: post data is null: park: {} vno: {}", park, cno);
                return null;
            }
            List<StreamDataResponse> list = response.getData();
            if (CollectionUtil.isNotEmpty(list)){
                for (StreamDataResponse d : list){
                    d.setCno(cno);
                }
            }
            return list;
        } catch (Exception e) {
            log.error("pullStream error: [cno: {}, st: {}, et: {}, url: {}]  message: {}", cno, st, et, url, e.getMessage());
            return null;
        }

    }
    public static List<StreamDataResponse> pullStreamByList(List<StreamDataRequest> sl, String url, String park){

        try {
            final String api = "/v2/smc/web/getmergeurl_v2";
            StreamResponse response = OkhttpUtil.doPostStream(new StreamRequest(sl), url+api);
            if (null == response || CollectionUtil.isEmpty(response.getData())){
                log.info("historyStream: post data is null: park: {}", park);
                return null;
            }
            List<StreamDataResponse> list = response.getData();
            if (CollectionUtil.isNotEmpty(list)){
                for (StreamDataResponse d : list){
                    d.setCno(d.getDevice_id());
                }
            }
            return list;
        } catch (Exception e) {
            log.error("pullStream error:  message: {}", e.getMessage());
            return null;
        }

    }

    public static List<Map<String, Object>> pullVType(String url){
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        OkHttpClient client = new OkHttpClient();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                VtypeDTO dto = JSON.parseObject(responseBody, VtypeDTO.class);
                return dto.getData();
            } else {
                log.error("pull Vtype failed:"+ JSON.toJSONString(response));
                return null;
            }
        } catch (IOException e) {
            log.error("pull Vtype Exception:", e);
            return null;
        }
    }



 /*   public static void main(String[] args) throws IOException {

        List<Map<String, Object>> list = pullVType("https://jaapi.scshyzh.cn:8743/gate-v8/reservation/getCarNumb?type=3,4");
        System.out.println(list.size());
    }*/


}
